package com.woniu.config;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.okhttp.OkDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author hq
 * @Date 2025/6/10$ 11:42$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Configuration
public class DockerConfig {
    @Value("${docker.host}")
    private String dockerHost;

    @Value("${docker.tls-verify}")
    private boolean tlsVerify;

    @Bean
    public DockerClient dockerClient() {
        try {
            DefaultDockerClientConfig.Builder configBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder()
                    .withDockerHost(dockerHost)
                    .withDockerTlsVerify(tlsVerify);

            DefaultDockerClientConfig config = configBuilder.build();

            DockerHttpClient httpClient = new OkDockerHttpClient.Builder()
                    .dockerHost(config.getDockerHost())
                    .sslConfig(config.getSSLConfig())
                    .build();

            DockerClient client = DockerClientImpl.getInstance(config, httpClient);
            client.pingCmd().exec(); // 测试连接
            System.out.println("✅ Docker连接成功");
            return client;
        } catch (Exception e) {
            throw new RuntimeException("❌ Docker连接失败: " + e.getMessage(), e);
        }
    }
}
